package com.orangelife.redis;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisShardInfo;
import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPool;

import com.orangelife.utils.IdUtil;

public class RedisClient {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		//
		RedisClient r = new RedisClient();

		ShardedJedis sj = null;
		sj = r.shardedJedis;

		String id1 = IdUtil.getMyRandom() + "";
		String id2 = IdUtil.getMyRandom() + "";
		String id3 = IdUtil.getMyRandom() + "";
		sj.set(id1, IdUtil.getMyRandom() + "");
		sj.set(id2, IdUtil.getMyRandom() + "");
		sj.set(id3, IdUtil.getMyRandom() + "");

		System.out.println(sj.get(id1));
		System.out.println(sj.get(id2));
		System.out.println(sj.get(id3));
		// nnnn n1=new nnnn(r.jedisPool);
		// nnnn n2=new nnnn(r.jedisPool);
		// nnnn n3=new nnnn(r.jedisPool);
		// nnnn n4=new nnnn(r.jedisPool);
		//
		// n1.start();
		// n2.start();
		// n3.start();
		// n4.start();
		//
		//
		//
		//
		//
		// Jedis j=null;
		// j=r.jedisPool.getResource();
		//
		// r.jedis.set("asdf", "sadf");
		// r.jedis.set("asdf", "sadf");
		// r.jedis.set("asdf", "sadf");
		// r.jedis.set("asdf1", "sadf");
		// r.jedis.set("asdf", "sadf");
		//
		// System.out.println(""+r.jedisPool.getNumActive());
		// System.out.println(""+r.jedisPool.getNumIdle());
		// System.out.println("3秒之后，获取key303对应的值："+r.shardedJedis.get("key303"));
		// System.out.println("OOOOOOOOOOOOOO"+r.shardedJedis.get("key001"));
		// // r.jedis.select(1);
		// r.jedis.set("asdf", "sadf");
		// // r.jedis.del("asdf");
		//
		// System.out.println(
		// r.jedis.hgetAll("f7f96987-ea50-4d46-915b-02509830dfad"));
		// r.shardedJedis.set("key001", "sadfsdaf");

		// r.ListOperate();
		// r.shardedJedis.expire("key001", 10);
		// r.KeyOperate1();
		// r.StringOperate();
		// this.jedis.hmget(key, files);
		// r.shardedJedis.hmget("e8407ee5-944e-4ad2-ba7c-e9420ce40d22","userID");
		// System.out.println(r.shardedJedis.get("e8407ee5-944e-4ad2-ba7c-e9420ce40d22"));

		// r.jedisPool.destroy();
	}

	private Jedis jedis;// 非切片额客户端连接
	private JedisPool jedisPool;// 非切片连接池
	private ShardedJedis shardedJedis;// 切片额客户端连接
	private ShardedJedisPool shardedJedisPool;// 切片连接池

	public RedisClient() {
		initialPool();
		initialShardedPool();
		shardedJedis = shardedJedisPool.getResource();
		jedis = jedisPool.getResource();

	}

	/**
	 * 初始化非切片池
	 */
	private void initialPool() {
		// 池基本配置
		JedisPoolConfig config = new JedisPoolConfig();
		// config.setMaxActive(20);
		config.setMaxIdle(110);

		config.setMaxWaitMillis(1000l);
		config.setTestOnBorrow(true);

		jedisPool = new JedisPool(config, "127.0.0.1", 6379);
		// jedisPool = new JedisPool(config,"www.17orange.com",6379);

	}

	/**
	 * 初始化切片池
	 */
	private void initialShardedPool() {
		// 池基本配置
		JedisPoolConfig config = new JedisPoolConfig();
		// config.setMaxActive(20);
		config.setMaxIdle(5);
		config.setMinIdle(100);
		config.setMaxWaitMillis(1000l);
		config.setTestOnBorrow(false);
		// slave链接
		List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>();
		JedisShardInfo je1 = new JedisShardInfo("127.0.0.1", 6379, "123456");

		shards.add(je1);
		JedisShardInfo je = new JedisShardInfo("127.0.0.1", 6379, "123456");
		shards.add(je);

		// 构造池
		shardedJedisPool = new ShardedJedisPool(config, shards);

	}

	public void show() {
		KeyOperate();
		StringOperate();
		ListOperate();
		SetOperate();
		SortedSetOperate();
		HashOperate();
		// jedisPool.returnResourceObject(jedis);;
		jedisPool.returnResourceObject(jedis);
		// shardedJedisPool.returnResource(shardedJedis);
	}

	private void KeyOperate() {

	}

	private void StringOperate() {
		System.out
				.println("======================String_1==========================");
		// 清空数据
		System.out.println("清空库中所有数据：" + jedis.flushDB());

		System.out.println("=============增=============");
		jedis.set("key001", "value001");
		jedis.set("key002", "value002");
		jedis.set("key003", "value003");
		System.out.println("已新增的3个键值对如下：");
		System.out.println(jedis.get("key001"));
		System.out.println(jedis.get("key002"));
		System.out.println(jedis.get("key003"));

		System.out.println("=============删=============");
		System.out.println("删除key003键值对：" + jedis.del("key003"));
		System.out.println("获取key003键对应的值：" + jedis.get("key003"));

		System.out.println("=============改=============");
		// 1、直接覆盖原来的数据
		System.out.println("直接覆盖key001原来的数据："
				+ jedis.set("key001", "value001-update"));
		System.out.println("获取key001对应的新值：" + jedis.get("key001"));
		// 2、直接覆盖原来的数据
		System.out.println("在key002原来值后面追加："
				+ jedis.append("key002", "+appendString"));
		System.out.println("获取key002对应的新值" + jedis.get("key002"));

		System.out.println("=============增，删，查（多个）=============");
		/**
		 * mset,mget同时新增，修改，查询多个键值对 等价于： jedis.set("name","ssss");
		 * jedis.set("jarorwar","xxxx");
		 */
		System.out.println("一次性新增key201,key202,key203,key204及其对应值："
				+ jedis.mset("key201", "value201", "key202", "value202",
						"key203", "value203", "key204", "value204"));
		System.out.println("一次性获取key201,key202,key203,key204各自对应的值："
				+ jedis.mget("key201", "key202", "key203", "key204"));
		System.out.println("一次性删除key201,key202："
				+ jedis.del(new String[] { "key201", "key202" }));
		System.out.println("一次性获取key201,key202,key203,key204各自对应的值："
				+ jedis.mget("key201", "key202", "key203", "key204"));
		System.out.println();

		// jedis具备的功能shardedJedis中也可直接使用，下面测试一些前面没用过的方法
		System.out
				.println("======================String_2==========================");
		// 清空数据
		System.out.println("清空库中所有数据：" + jedis.flushDB());

		System.out.println("=============新增键值对时防止覆盖原先值=============");
		System.out.println("原先key301不存在时，新增key301："
				+ shardedJedis.setnx("key301", "value301"));
		System.out.println("原先key302不存在时，新增key302："
				+ shardedJedis.setnx("key302", "value302"));
		System.out.println("当key302存在时，尝试新增key302："
				+ shardedJedis.setnx("key302", "value302_new"));
		System.out.println("获取key301对应的值：" + shardedJedis.get("key301"));
		System.out.println("获取key302对应的值：" + shardedJedis.get("key302"));

		System.out.println("=============超过有效期键值对被删除=============");
		// 设置key的有效期，并存储数据
		System.out.println("新增key303，并指定过期时间为2秒"
				+ shardedJedis.setex("key303", 10, "key303-2second"));
		System.out.println("获取key303对应的值：" + shardedJedis.get("key303"));
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
		}
		System.out.println("3秒之后，获取key303对应的值：" + shardedJedis.get("key303"));

		System.out.println("=============获取原值，更新为新值一步完成=============");
		System.out.println("key302原值："
				+ shardedJedis.getSet("key302", "value302-after-getset"));
		System.out.println("key302新值：" + shardedJedis.get("key302"));

		System.out.println("=============获取子串=============");
		System.out.println("获取key302对应值中的子串："
				+ shardedJedis.getrange("key302", 5, 7));
	}

	private void ListOperate() {
		shardedJedis.lpush("stringlists", "vector");
		shardedJedis.lpush("stringlists", "ArrayList");
		shardedJedis.lpush("stringlists", "vector");
		shardedJedis.lpush("stringlists", "vector");
		shardedJedis.lpush("stringlists", "LinkedList");
		shardedJedis.lpush("stringlists", "MapList");
		shardedJedis.lpush("stringlists", "SerialList");
		shardedJedis.lpush("stringlists", "HashList");
		shardedJedis.lpush("numberlists", "3");
		shardedJedis.lpush("numberlists", "1");
		shardedJedis.lpush("numberlists", "5");
		shardedJedis.lpush("numberlists", "2");
		System.out.println("=============增=============");
		System.out.println("向sets集合中加入元素element001："
				+ jedis.sadd("sets", "element001"));
		System.out.println("向sets集合中加入元素element002："
				+ jedis.sadd("sets", "element002"));
		System.out.println("向sets集合中加入元素element003："
				+ jedis.sadd("sets", "element003"));
		System.out.println("向sets集合中加入元素element004："
				+ jedis.sadd("sets", "element004"));
		System.out.println("查看sets集合中的所有元素:" + jedis.smembers("sets"));

		System.out.println("hashs中添加key001和value001键值对："
				+ shardedJedis.hset("hashs", "key001", "value001"));
		System.out.println("hashs中添加key002和value002键值对："
				+ shardedJedis.hset("hashs", "key002", "value002"));
		System.out.println("hashs中添加key003和value003键值对："
				+ shardedJedis.hset("hashs", "key003", "value003"));
		shardedJedis.expire("hashs", 10);
	}

	private void SetOperate() {

	}

	private void SortedSetOperate() {

	}

	private void HashOperate() {

	}

	private void KeyOperate1() {
		System.out
				.println("======================key==========================");
		// 清空数据
		// System.out.println("清空库中所有数据："+jedis.flushDB());
		// 判断key否存在
		System.out.println("判断key999键是否存在：" + shardedJedis.exists("key999"));
		System.out.println("新增key001,value001键值对："
				+ shardedJedis.set("key001", "value001"));
		System.out.println("判断key001是否存在：" + shardedJedis.exists("key001"));
		// 输出系统中所有的key
		System.out.println("新增key002,value002键值对："
				+ shardedJedis.set("key002", "value002"));
		System.out.println("系统中所有键如下：");
		Set<String> keys = jedis.keys("*");
		Iterator<String> it = keys.iterator();
		while (it.hasNext()) {
			String key = it.next();
			System.out.println(key);
		}

		// 删除某个key,若key不存在，则忽略该命令。
		// System.out.println("系统中删除key002: "+jedis.del("key002"));
		System.out.println("判断key002是否存在：" + shardedJedis.exists("key002"));
		// 设置 key001的过期时间
		System.out.println("设置 key001的过期时间为5秒:" + jedis.expire("key001", 5));
		try {
			Thread.sleep(2000);
		} catch (InterruptedException e) {
		}

		// 查看某个key的剩余生存时间,单位【秒】.永久生存或者不存在的都返回-1
		System.out.println("查看key001的剩余生存时间：" + jedis.ttl("key001"));
		// 移除某个key的生存时间
		// System.out.println("移除key001的生存时间："+jedis.persist("key001"));
		System.out.println("查看key001的剩余生存时间：" + jedis.ttl("key001"));
		// 查看key所储存的值的类型
		System.out.println("查看key所储存的值的类型：" + jedis.type("key001"));
		/*
		 * 一些其他方法：1、修改键名：jedis.rename("key6", "key0");
		 * 2、将当前db的key移动到给定的db当中：jedis.move("foo", 1)
		 */
	}
}

class nnnn extends Thread {

	JedisPool jjj = null;

	public nnnn(JedisPool j) {

		this.jjj = j;

	}

	public void run() {

		for (int i = 0; i < 1000; i++) {

			Jedis j = null;
			try {
				j = this.jjj.getResource();
				System.out.println(i + "****" + j.get("asdf"));
				System.out.println("getNumWaiters" + this.jjj.getNumWaiters());
				System.out.println("getNumIdle:" + this.jjj.getNumIdle());
				System.out.println("getNumActive" + this.jjj.getNumActive());
			} finally {

				if (j != null) {

					j.close();
				}

			}

		}

	}
}
